<template>
  <div class="invoice-management-page">
    <!-- 统计卡片 -->
    <div class="stats-card">
      <div class="stats-row">
        <div class="stats-item">
          <div class="stats-value">{{ stats.totalInvoices }}</div>
          <div class="stats-label">发票总数</div>
        </div>
        <div class="stats-item">
          <div class="stats-value">¥{{ formatAmount(stats.totalAmount) }}</div>
          <div class="stats-label">发票总额</div>
        </div>
        <div class="stats-item">
          <div class="stats-value">{{ stats.verifiedCount }}</div>
          <div class="stats-label">已验证</div>
        </div>
        <div class="stats-item">
          <div class="stats-value">{{ stats.pendingCount }}</div>
          <div class="stats-label">待验证</div>
        </div>
      </div>
    </div>
    
    <!-- 筛选区域 -->
    <div class="filter-section">
      <van-dropdown-menu>
        <van-dropdown-item v-model="filter.type" :options="typeOptions" />
        <van-dropdown-item v-model="filter.status" :options="statusOptions" />
        <van-dropdown-item title="时间范围" ref="dateDropdown">
          <div class="date-filter">
            <van-cell title="选择时间范围">
              <template #right-icon>
                <van-icon name="close" @click="resetDateFilter" />
              </template>
            </van-cell>
            <div class="date-range">
              <van-field
                readonly
                label="开始日期"
                :model-value="formatDate(filter.startDate)"
                placeholder="请选择开始日期"
                @click="showStartDatePicker = true"
              />
              <van-field
                readonly
                label="结束日期"
                :model-value="formatDate(filter.endDate)"
                placeholder="请选择结束日期"
                @click="showEndDatePicker = true"
              />
            </div>
            <div class="filter-buttons">
              <van-button plain block @click="resetDateFilter">重置</van-button>
              <van-button type="primary" block @click="applyDateFilter">确定</van-button>
            </div>
          </div>
        </van-dropdown-item>
      </van-dropdown-menu>
      
      <!-- 日期选择弹窗 -->
      <van-calendar v-model:show="showStartDatePicker" 
                   @confirm="onStartDateConfirm"
                   :show-confirm="true"
                   color="#1989fa"/>
                   
      <van-calendar v-model:show="showEndDatePicker" 
                   @confirm="onEndDateConfirm"
                   :show-confirm="true"
                   color="#1989fa"/>
    </div>
    
    <!-- 发票列表 -->
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh" success-text="刷新成功">
      <van-list
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <template v-if="invoiceList.length === 0 && !loading">
          <EmptyState 
            text="暂无发票记录" 
            actionText="扫描发票" 
            @action="scanInvoice" 
          />
        </template>
        
        <div v-else class="invoice-list">
          <van-swipe-cell
            v-for="item in invoiceList"
            :key="item.id"
            :before-close="beforeClose"
          >
            <van-cell clickable @click="viewInvoiceDetail(item.id)">
              <template #title>
                <div class="invoice-title">{{ item.title }}</div>
                <div class="invoice-code">发票代码: {{ item.code }}</div>
              </template>
              <template #label>
                <div class="invoice-info">
                  <div class="invoice-date">{{ item.date }}</div>
                  <div class="invoice-type">{{ getTypeName(item.type) }}</div>
                </div>
                <div class="invoice-status-row">
                  <van-tag :type="getStatusType(item.status)" size="medium">
                    {{ getStatusText(item.status) }}
                  </van-tag>
                  <div class="invoice-amount">¥{{ formatAmount(item.amount) }}</div>
                </div>
              </template>
            </van-cell>
            <template #right>
              <van-button
                square
                text="查看"
                type="primary"
                class="swipe-button"
                @click="viewInvoiceDetail(item.id)"
              />
            </template>
          </van-swipe-cell>
        </div>
      </van-list>
    </van-pull-refresh>
    
    <!-- 操作按钮组 -->
    <div class="action-buttons">
      <van-button 
        icon="scan" 
        type="primary" 
        round 
        size="small" 
        @click="scanInvoice" 
        class="action-button"
      >
        扫描发票
      </van-button>
      <van-button 
        icon="photograph" 
        type="info" 
        round 
        size="small" 
        @click="uploadInvoice" 
        class="action-button"
      >
        上传发票
      </van-button>
      <van-button 
        icon="wechat" 
        type="success" 
        round 
        size="small" 
        @click="importFromWechat" 
        class="action-button"
      >
        微信导入
      </van-button>
    </div>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { 
  NavBar, DropdownMenu, DropdownItem, Cell, Icon, Calendar,
  Button, Field, List, PullRefresh, Tag, SwipeCell,
  Dialog, Toast
} from 'vant'
import EmptyState from '@/components/common/EmptyState.vue'
import CustomPopup from '@/components/CustomPopup.vue'

export default {
  name: 'MobileFinanceInvoice',
  components: {
    vanNavBar: NavBar,
    vanDropdownMenu: DropdownMenu,
    vanDropdownItem: DropdownItem,
    vanCell: Cell,
    vanIcon: Icon,
    vanCalendar: Calendar,
    vanButton: Button,
    vanField: Field,
    vanList: List,
    vanPullRefresh: PullRefresh,
    vanTag: Tag,
    vanSwipeCell: SwipeCell,
    EmptyState,
    CustomPopup
  },
  setup() {
    const router = useRouter()
    const store = useStore()
    const dateDropdown = ref(null)
    
    // 列表状态
    const loading = ref(false)
    const refreshing = ref(false)
    const finished = ref(false)
    const invoiceList = ref([])
    const page = ref(1)
    const pageSize = ref(10)
    
    // 统计数据
    const stats = reactive({
      totalInvoices: 42,
      totalAmount: 18765.30,
      verifiedCount: 36,
      pendingCount: 6
    })
    
    // 筛选条件
    const filter = reactive({
      type: 'all',
      status: 'all',
      startDate: '',
      endDate: ''
    })
    
    // 日期选择器状态
    const showStartDatePicker = ref(false)
    const showEndDatePicker = ref(false)
    
    // 下拉选项
    const typeOptions = [
      { text: '全部类型', value: 'all' },
      { text: '增值税专票', value: 'vat-special' },
      { text: '增值税普票', value: 'vat-normal' },
      { text: '电子发票', value: 'electronic' },
      { text: '其他票据', value: 'other' }
    ]
    
    const statusOptions = [
      { text: '全部状态', value: 'all' },
      { text: '已验证', value: 'verified' },
      { text: '待验证', value: 'pending' },
      { text: '已使用', value: 'used' },
      { text: '已作废', value: 'invalid' }
    ]
    
    // 获取发票类型名称
    const getTypeName = (type) => {
      const typeMap = {
        'vat-special': '增值税专票',
        'vat-normal': '增值税普票',
        'electronic': '电子发票',
        'other': '其他票据'
      }
      return typeMap[type] || type
    }
    
    // 获取状态类型
    const getStatusType = (status) => {
      const statusMap = {
        'verified': 'success',
        'pending': 'warning',
        'used': 'primary',
        'invalid': 'danger'
      }
      return statusMap[status] || 'default'
    }
    
    // 获取状态文本
    const getStatusText = (status) => {
      const statusMap = {
        'verified': '已验证',
        'pending': '待验证',
        'used': '已使用',
        'invalid': '已作废'
      }
      return statusMap[status] || status
    }
    
    // 格式化金额
    const formatAmount = (amount) => {
      return parseFloat(amount).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
    }
    
    // 格式化日期
    const formatDate = (date) => {
      if (!date) return ''
      if (typeof date === 'string') return date
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
    }
    
    // 返回上一页
    const onBackClick = () => {
      router.back()
    }
    
    // 下拉刷新
    const onRefresh = () => {
      finished.value = false
      page.value = 1
      fetchInvoiceList(true)
    }
    
    // 加载更多
    const onLoad = () => {
      fetchInvoiceList()
    }
    
    // 加载发票列表
    const fetchInvoiceList = (isRefresh = false) => {
      if (isRefresh) {
        page.value = 1
        finished.value = false
        invoiceList.value = []
      }
      
      loading.value = true
      
      // 模拟API请求
      setTimeout(() => {
        const newItems = generateMockData(page.value, pageSize.value, filter)
        if (isRefresh) {
          invoiceList.value = newItems
        } else {
          invoiceList.value = [...invoiceList.value, ...newItems]
        }
        
        loading.value = false
        if (refreshing.value) refreshing.value = false
        
        // 判断是否还有更多数据
        if (newItems.length < pageSize.value) {
          finished.value = true
        } else {
          page.value += 1
        }
      }, 1000)
    }
    
    // 生成模拟数据
    const generateMockData = (page, pageSize, filter) => {
      const mockInvoices = [
        {
          id: 1,
          title: '某科技有限公司',
          code: '044001900311',
          date: '2023-10-15',
          type: 'vat-special',
          status: 'verified',
          amount: 1280.00
        },
        {
          id: 2,
          title: '某餐饮有限公司',
          code: '044001900312',
          date: '2023-10-12',
          type: 'electronic',
          status: 'verified',
          amount: 328.50
        },
        {
          id: 3,
          title: '某物流有限公司',
          code: '044001900313',
          date: '2023-10-08',
          type: 'vat-normal',
          status: 'used',
          amount: 560.00
        },
        {
          id: 4,
          title: '某酒店有限公司',
          code: '044001900314',
          date: '2023-10-05',
          type: 'electronic',
          status: 'verified',
          amount: 1680.00
        },
        {
          id: 5,
          title: '某办公用品公司',
          code: '044001900315',
          date: '2023-09-28',
          type: 'vat-normal',
          status: 'pending',
          amount: 459.80
        },
        {
          id: 6,
          title: '某加油站',
          code: '044001900316',
          date: '2023-09-25',
          type: 'electronic',
          status: 'verified',
          amount: 380.00
        },
        {
          id: 7,
          title: '某航空公司',
          code: '044001900317',
          date: '2023-09-20',
          type: 'electronic',
          status: 'verified',
          amount: 1580.00
        },
        {
          id: 8,
          title: '某超市',
          code: '044001900318',
          date: '2023-09-18',
          type: 'vat-normal',
          status: 'pending',
          amount: 269.50
        },
        {
          id: 9,
          title: '某软件公司',
          code: '044001900319',
          date: '2023-09-15',
          type: 'vat-special',
          status: 'invalid',
          amount: 3280.00
        },
        {
          id: 10,
          title: '某电子商务公司',
          code: '044001900320',
          date: '2023-09-10',
          type: 'electronic',
          status: 'used',
          amount: 782.00
        }
      ]
      
      // 根据筛选条件过滤
      let filteredData = [...mockInvoices]
      
      if (filter.type !== 'all') {
        filteredData = filteredData.filter(item => item.type === filter.type)
      }
      
      if (filter.status !== 'all') {
        filteredData = filteredData.filter(item => item.status === filter.status)
      }
      
      if (filter.startDate && filter.endDate) {
        const start = new Date(filter.startDate).getTime()
        const end = new Date(filter.endDate).getTime()
        
        filteredData = filteredData.filter(item => {
          const itemDate = new Date(item.date).getTime()
          return itemDate >= start && itemDate <= end
        })
      }
      
      // 模拟分页
      const startIndex = (page - 1) * pageSize
      const result = []
      
      for (let i = startIndex; i < startIndex + pageSize && i < filteredData.length; i++) {
        result.push(filteredData[i])
      }
      
      return result
    }
    
    // 开始日期确认
    const onStartDateConfirm = (date) => {
      filter.startDate = date
      showStartDatePicker.value = false
    }
    
    // 结束日期确认
    const onEndDateConfirm = (date) => {
      filter.endDate = date
      showEndDatePicker.value = false
    }
    
    // 应用日期筛选
    const applyDateFilter = () => {
      dateDropdown.value.toggle()
      fetchInvoiceList(true)
    }
    
    // 重置日期筛选
    const resetDateFilter = () => {
      filter.startDate = ''
      filter.endDate = ''
    }
    
    // 滑动单元格关闭前
    const beforeClose = ({ position, instance }) => {
      if (position === 'right') {
        instance.close()
      }
      return true
    }
    
    // 查看发票详情
    const viewInvoiceDetail = (id) => {
      router.push(`/new/finance/invoice/${id}`)
    }
    
    // 扫描发票
    const scanInvoice = () => {
      Toast('启动发票扫描')
      // 模拟调用原生扫描功能
      setTimeout(() => {
        Dialog.alert({
          title: '扫描成功',
          message: '发票信息已成功识别并保存'
        }).then(() => {
          // 刷新列表
          onRefresh()
        })
      }, 1500)
    }
    
    // 上传发票
    const uploadInvoice = () => {
      Toast('请选择发票图片')
      // 这里可以调用图片上传功能
    }
    
    // 从微信发票夹导入
    const importFromWechat = () => {
      Toast.loading({
        message: '正在连接微信...',
        forbidClick: true,
      });
      
      // 检查是否在微信环境中
      const isWechatBrowser = /MicroMessenger/i.test(navigator.userAgent);
      if (!isWechatBrowser) {
        Toast.clear();
        Dialog.alert({
          title: '提示',
          message: '请在微信内打开页面使用此功能'
        });
        return;
      }
      
      // 确保微信JS-SDK已加载
      if (typeof wx === 'undefined') {
        Toast.clear();
        Toast.fail('微信SDK加载失败');
        return;
      }
      
      // 请求用户授权
      Dialog.confirm({
        title: '微信发票导入',
        message: '是否授权访问微信发票夹？导入后的发票将自动进行验真。',
        confirmButtonText: '授权导入',
        cancelButtonText: '取消'
      })
      .then(() => {
        // 用户点击确认按钮
        Toast.loading({
          message: '正在请求微信发票...',
          forbidClick: true,
        });
        
        // 调用微信发票接口
        wx.invoke('chooseInvoice', {
          timestamp: store.state.wxConfig?.timestamp || '', // 从store中获取配置
          nonceStr: store.state.wxConfig?.nonceStr || '',
          signType: 'SHA1',
          cardSign: store.state.wxConfig?.cardSign || '' // 卡券签名
        }, function(res) {
          Toast.clear();
          
          if (res.err_msg == "chooseInvoice:ok") {
            const invoiceList = res.choose_invoice_info ? JSON.parse(res.choose_invoice_info) : [];
            
            if (invoiceList.length === 0) {
              Toast('未选择任何发票');
              return;
            }
            
            // 显示导入中
            Toast.loading({
              message: `正在导入${invoiceList.length}张发票...`,
              forbidClick: true,
            });
            
            // 调用后端API保存发票信息
            // 这里需要替换为实际的API调用
            saveWechatInvoices(invoiceList).then(result => {
              Toast.clear();
              Dialog.alert({
                title: '导入成功',
                message: `已成功从微信发票夹导入${result.successCount}张发票`
              }).then(() => {
                // 刷新列表
                onRefresh();
              });
            }).catch(error => {
              Toast.clear();
              Dialog.alert({
                title: '导入失败',
                message: error.message || '导入发票时发生错误'
              });
            });
          } else {
            Toast('获取发票失败: ' + (res.err_desc || res.err_msg));
          }
        });
      })
      .catch(() => {
        // 用户取消
        Toast.clear();
        Toast('已取消导入');
      });
    }
    
    // 保存微信发票到服务器
    const saveWechatInvoices = (invoiceList) => {
      return new Promise((resolve, reject) => {
        // TODO: 替换为实际的API调用
        // 模拟API调用
        setTimeout(() => {
          // 假设所有发票都成功导入
          resolve({
            successCount: invoiceList.length,
            failCount: 0
          });
        }, 1500);
      });
    }
    
    // 初始化数据
    onMounted(() => {
      fetchInvoiceList()
    })
    
    return {
      invoiceList,
      loading,
      finished,
      refreshing,
      filter,
      typeOptions,
      statusOptions,
      stats,
      showStartDatePicker,
      showEndDatePicker,
      dateDropdown,
      getTypeName,
      getStatusType,
      getStatusText,
      formatAmount,
      formatDate,
      onBackClick,
      onRefresh,
      onLoad,
      onStartDateConfirm,
      onEndDateConfirm,
      applyDateFilter,
      resetDateFilter,
      beforeClose,
      viewInvoiceDetail,
      scanInvoice,
      uploadInvoice,
      importFromWechat,
      saveWechatInvoices
    }
  }
}
</script>

<style scoped>
.invoice-management-page {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding-bottom: 80px;
}

.stats-card {
  background-color: #fff;
  margin: 12px;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.stats-row {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px 12px;
}

.stats-item {
  text-align: center;
}

.stats-value {
  font-size: 18px;
  font-weight: 500;
  color: #1989fa;
  margin-bottom: 4px;
}

.stats-label {
  font-size: 12px;
  color: #969799;
}

.filter-section {
  margin-bottom: 12px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.date-filter {
  padding: 16px;
}

.date-range {
  margin-bottom: 16px;
}

.filter-buttons {
  display: flex;
  gap: 12px;
}

.invoice-list {
  margin: 0 12px;
}

.invoice-title {
  font-size: 15px;
  font-weight: 500;
  margin-bottom: 4px;
}

.invoice-code {
  font-size: 12px;
  color: #969799;
}

.invoice-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 6px;
  font-size: 12px;
  color: #646566;
}

.invoice-status-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.invoice-amount {
  font-weight: 500;
  color: #ff976a;
}

.swipe-button {
  height: 100%;
}

.action-buttons {
  position: fixed;
  bottom: 20px;
  left: 0;
  right: 0;
  display: flex;
  justify-content: center;
  gap: 16px;
  z-index: 10;
}

.action-button {
  padding: 0 24px;
  height: 40px;
  border-radius: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 移动端适配 */
@media (max-width: 360px) {
  .stats-row {
    grid-template-columns: repeat(2, 1fr);
  }
}

/* 暗黑模式适配 */
@media (prefers-color-scheme: dark) {
  .stats-card,
  .invoice-list .van-cell {
    background-color: #1c1c1e;
  }
  
  .stats-value {
    color: #4088f4;
  }
  
  .invoice-title {
    color: #f5f5f5;
  }
  
  .invoice-code,
  .invoice-info {
    color: #8e8e93;
  }
}
</style> 